import { BaseRequest } from './BaseRequest'
import { IObject, Ictr } from './types'

/**queryString */
function queryString(json: IObject) {
  if (!json) return ''
  return new URLSearchParams(json).toString()
}

export class McRequest extends BaseRequest {
  get(url: string, data?: IObject, ctr?: Ictr) {
    return this.request(url + (data ? `?${queryString(data)}` : ''), { method: 'get' }, ctr)
  }
  post(url: string, data?: IObject, ctr?: Ictr) {
    return this.request(
      url,
      {
        data: data ? queryString(data) : '',
        method: 'post',
        headers: {
          'content-type': 'application/x-www-form-urlencoded'
        }
      },
      ctr
    )
  }
  postForm(url: string, data?: IObject, ctr?: Ictr) {
    return this.post(url, data, ctr)
  }
  postJson(url: string, data?: IObject, ctr?: Ictr) {
    return this.request(
      url,
      {
        method: 'post',
        data: JSON.stringify(data),
        headers: { 'content-type': 'application/json;charset=UTF-8' }
      },
      ctr
    )
  }
  postFormData(url: string, data: FormData, ctr?: Ictr) {
    return this.request(url, { method: 'post', data }, ctr)
  }
}
